#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: ix-smbpasswd
# REQUIRE: samba_server

. /etc/rc.subr

generate_smbpasswd()
{
	local IFS="|"
	local f="ldap_bindpw"
	eval local $f
	local sf=$(var_to_sf $f)
	RO_FREENAS_CONFIG=$(ro_sqlite ${name} 2> /tmp/${name}.fail && rm /tmp/${name}.fail)
	trap 'rm -f ${RO_FREENAS_CONFIG}' EXIT

	${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "
	SELECT
		$sf

	FROM
		services_services,
		directoryservice_ldap

	WHERE (
		srv_service = 'ldap' and
		srv_enable = 1
	)

	ORDER BY
		-directoryservice_ldap.id

	LIMIT 1 " | \
	while eval read $f
	do
		if [ -n "${ldap_bindpw}" ]; then
			/usr/local/bin/smbpasswd -w "$(/usr/local/bin/midclt notifier.pwenc_decrypt ${ldap_bindpw})" >/dev/null 2>&1
		fi
	done
}

name="ix-smbpasswd"
start_cmd='generate_smbpasswd'
stop_cmd=':'

load_rc_config $name
run_rc_command "$1"
